/*
 * File:   rf_module.c
 * Author: craigjb
 *
 * Created on April 23, 2013, 2:15 PM
 */

#include "rf_module.h"
#include <spi.h>
#include "nrf24l01.h"
#include "tick.h"
#include "sensors.h"
#include "states.h"

static unsigned g_resumeToState = PRIMARY_STATE_INIT;
unsigned set = 0;

/* ************************************************************************** */
void RFModuleInit(void)
{
    // set CSN, CE as outputs
    // CSN -> RB11
    // CE  ->
    // set IRQ as input
    _TRISB7 = 1;
    _TRISB11 = 0;
    _TRISB3 = 0;

    // map SPI1 pins
    _SDI1R = 14;
    _RP13R = 7;
    _RP12R = 8;
    
    OpenSPI1(ENABLE_SCK_PIN & ENABLE_SDO_PIN & SPI_MODE8_ON & SPI_SMP_OFF &
            SPI_CKE_OFF & SLAVE_ENABLE_OFF & CLK_POL_ACTIVE_HIGH &
            MASTER_ENABLE_ON & SEC_PRESCAL_1_1 & PRI_PRESCAL_4_1,
            FRAME_ENABLE_OFF & SPI_ENH_BUFF_DISABLE,
            SPI_ENABLE & SPI_IDLE_CON & SPI_RX_OVFLOW_CLR);

    // startup NRF module for RX
    nrf24l01_initialize_debug(true, 2, false);

    volatile unsigned char conf = (int)nrf24l01_get_rx_pw(0);
    conf = nrf24l01_get_config();

    set = 0;
    g_resumeToState = PRIMARY_STATE_SEARCH_IR;
}

void RFModuleProcess(void)
{
    unsigned char data[2];
    // check for data on the NRF module
    if (nrf24l01_irq_pin_active() && nrf24l01_irq_rx_dr_active())
    {
        nrf24l01_irq_clear_all();
        nrf24l01_read_rx_payload(data, 2);

        if (data[0] == 'p' && !set) {
            RFPauseReceived();
        } else if (data[0] == 'r' && set) {
            RFResumeReceived();
        }
        data[0] = '\0';
    }
}

void RFPauseReceived(void)
{
    PauseTick();
    PauseSensors();
    OC1CON &= 0xFFF8;
    OC2CON &= 0xFFF8;
    _LATB6 = 0;
    _LATB9 = 0;
    _LATB8 = 0;
    _LATB5 = 0;
    g_resumeToState = GetCurrentPrimaryState();
    SetCurrentPrimaryState(PRIMARY_STATE_DO_NOTHING);
    set = 1;
}

void RFResumeReceived(void)
{
    SetCurrentPrimaryState(g_resumeToState);
    ResumeTick();
    StartSensors();
    OC1CON |= 0x5;
    OC2CON |= 0x5;
    set = 0;
}

